<template>
  <div>
    <Mytable :arr="list">
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #Mytable="{ val, index }">
        <!--  val : obj  -->
        <!--   val : obj2 -->
        <td>{{ val.id }}</td>
        <td>{{ val.goods_name }}</td>
        <td>{{ val.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            type="text"
            v-if="val.inputVisible"
            v-focus
            @blur="blur(val)"
            @keyup.enter="add(val)"
            v-model="val.inputValue"
            @keyup.esc="esc(val)"
          />
          <button
            class="btn btn-primary btn-sm add-tag"
            v-else
            @click="val.inputVisible = true"
          >
            +Tag
          </button>
          <span v-for="(str, index) in val.tags" :key="index">{{ str }}</span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="del(index)">
            删除
          </button>
        </td>
      </template>
    </Mytable>
  </div>
</template>

<script>
import axios from "axios";
import Mytable from "../components/Mytable";
export default {
  components: {
    Mytable,
  },
  data() {
    return {
      list: [],
    };
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      },
    },
  },
  created() {
    axios({
      url: "https://www.escook.cn/api/goods",
    }).then((res) => {
      this.list = res.data.data;
    });
  },
  methods: {
    del(index) {
      this.list.splice(index, 1);
    },
    blur(obj) {
      obj.inputVisible = false;
    },
    add(obj) {
      obj.tags.push(obj.inputValue);
      obj.inputVisible = false;
    },
    esc(obj) {
      obj.inputValue = "";
    },
  },
};
</script>

<style>
.main {
  padding: 45px 0 50px 0;
}
</style>